import {PlusOutlined} from '@ant-design/icons';
import {useRequest} from '@umijs/hooks';
import {Button, Form, Input, message, Modal, Switch, Upload, TreeSelect, Tree, Card, Cascader, Radio} from 'antd';
import {Store} from 'rc-field-form/lib/interface';
import React, {useEffect, useState} from 'react';
import cookie from 'react-cookies';
import {useDispatch} from 'react-redux';
import {getSecretString} from '../../../../../utils/encrypt';
import getImgInfo from '../../../../../utils/getImgInfo';
import {fetchRequest} from '../../../../../utils/Request';
import {url} from '../../../../../utils/url';
import actionTypes from '../../../actionTypes';
import '../../index.css';

interface InfoState {
    whiteCard: boolean,
    face: boolean,
    blackCard: boolean,
    blackCardCode: string
}

interface ValidateState {
    state: "" | "success" | "warning" | "error" | "validating" | undefined,
    help: string | undefined,

}


interface OpenTypeInfo {
    userName: string,
    phone: string,
    whiteCard: boolean,
    whiteCardCode: string,
    face: boolean

}

interface RequestAddres {
    level: number,
    collegeId: string,
    collegeAreaId: string,
    building: string,
    unit: string,
    floor: string
}

export default function ModifyStduentAddressEntrance(props: any) {

    const [state, setstate] = useState<InfoState>({
        whiteCard: props.content.whiteCard,
        face: props.content.face, blackCard: props.content.blackCard,
        blackCardCode: props.content.blackCardCode
    })


    const [validateState, setvalidateState] = useState<ValidateState>({state: undefined, help: undefined})

    const layout = {
        labelCol: {span: 5},
        wrapperCol: {span: 14},
    };

    const tailLayout = {
        wrapperCol: {offset: 5, span: 14},
    };

    const [form] = Form.useForm();

    const dispatch = useDispatch()

    const [addressNode, setAddressNode] = useState(props.content.addressNode)

    const {info} = props;

    function onFinish(value: Store) {
        //TODO 后续进行请求并决定是否跳转到下一步

         console.log(value)

        if (value.isHavingDorm && value.allAddress?.length !== 6) {
            Modal.error({content: "宿舍地址请完整选择！"});
            return false;
        }

        if (!value.isHavingDorm && value.allAddress?.length !== 2) {
            Modal.error({content: "宿舍地址请完整选择！"});
            return false;
        }

        const data = [];
        console.log(value)
        submitOpenType.run(
            {value: value})
        // props.onNext()
    }


    //提交开门方式的接口
    async function submitOpenTypeRequest(value: any) {

        console.log(value)
        const params = {
            accessCardId: props.content.content.accessCardId,
            collegeId: value.value.allAddress[0],
            collegeAreaId: value.value.allAddress[1],
            building: value.value.allAddress[2],
            unit: value.value.allAddress[3],
            floor: value.value.allAddress[4],
            room: value.value.allAddress[5],
            "userTypeId": 5,
            "startDate": props.content.content.startDate,
            "endDate": props.content.content.endDate,
            "face": String(props.content.content.openType.openType.face),
            "whiteCard": String(props.content.content.openType.openType.whiteCard),
            "blackCard": String(props.content.content.openType.openType.blackCard),
            isHavingDorm: value.value.isHavingDorm

        }
        try {
            const json = await fetchRequest(url.MODIFY_SUSHE, params);

            if (json.success) {
                props.modifyAddressSuccess();
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message);
        }
    }

    const submitOpenType = useRequest(submitOpenTypeRequest, {
        manual: true,
        loadingDelay: 200
    })
    const loadData = (selectedOptions: any) => {
        //
        const targetOption = selectedOptions[selectedOptions.length - 1];
        //修改宿舍loading

        const isHavingDorm = form.getFieldValue('isHavingDorm')//是否有宿舍
        const level = targetOption?.['level']
        targetOption.loading = true;
        if (!isHavingDorm) {
            if (level == 1) {

                return
            }
        }


        targetOption.loading = false;
        let jsondata: any = [];
        let addrArray: any = [];
        selectedOptions.forEach(function (item: any) {
            addrArray.push(item['value'])
        })

        getAllAdd({
            "level": targetOption['level'] + 1,
            "collegeId": typeof addrArray[0] === "undefined" ? "" : addrArray[0],
            "collegeAreaId": typeof addrArray[1] === "undefined" ? "" : addrArray[1],
            "building": typeof addrArray[2] === "undefined" ? "" : addrArray[2],
            "unit": typeof addrArray[3] === "undefined" ? "" : addrArray[3],
            "floor": typeof addrArray[4] === "undefined" ? "" : addrArray[4],

        }).then((e: any) => {
            jsondata = e
            if (!isHavingDorm) {
                if (level === 0) {
                    jsondata.map((item: any) => item.isLeaf = true)
                    console.log(jsondata)
                }
            }

            targetOption.loading = false;
            targetOption.children = jsondata;


            setAddressNode([...addressNode])
        })
    };

    async function getAllAdd(params: RequestAddres) {
        try {
            const json = await fetchRequest(url.GET_ADDRESS_NODE, params);
            if (json.success) {
                return json.data
            } else {
                return []
            }
        } catch (error: any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const OnChange = (value: any, selectedOptions: any) => {


    };
    const [requestAddress, setRequestAddress] = useState<any>({
        "level": 0,
        "collegeId": "",
        "collegeAreaId": "",
        "building": "",
        "unit": "",
        "floor": ""
    })


    const getAllAddress = useRequest(getAllAddressNode, {
        manual: true,
        loadingDelay: 200
    })

    async function getAllAddressNode(params: RequestAddres) {
        try {
            const json = await fetchRequest(url.GET_ADDRESS_NODE, params);
            if (json.success) {
                setAddressNode(json.data)
                // return json.data
            } else {
                // console.log('getAllAddressNode:',json)
                // return []
            }
        } catch (error: any) {
            // console.log('getAllAddressNode:',error)
        }
    }

    function filter(inputValue: any, path: any[]) {
        return path.some((option: any) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    }


    const isHavingDormChange = async (e: any) => {
        form.setFieldsValue({
            allAddress: []
        })

    }


    return (
        <Form
            form={form} {...layout} initialValues={{
            userName: props.content.userName,
            phone: typeof props.content.phone === "undefined" || props.content.phone === null ? "" : props.content.phone,
            whiteCardCode: props.content.whiteCardCode,
            face: props.content.face,
            "isHavingDorm": 0
        }} onFinish={onFinish}>
            <Form.Item className="form-control-item" name="allAddress" label="宿舍地址">

                <Cascader
                    placeholder="请输入宿舍地址"
                    options={addressNode}
                    loadData={loadData}
                    changeOnSelect
                    onChange={OnChange}
                    showSearch={{filter}}

                />
            </Form.Item>

            <Form.Item label="是否有宿舍"
                       name="isHavingDorm"
                       className="form-control-item"
            >
                <Radio.Group onChange={isHavingDormChange}>
                    <Radio value={0}>否</Radio>
                    <Radio value={1}>是</Radio>
                </Radio.Group>
            </Form.Item>


            <br/>
            <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit" loading={submitOpenType.loading}>提交</Button>
            </Form.Item>


        </Form>
    )
}
